<template>
  <!-- 合同变更新增编辑查看 -->
  <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="state != 3 ? rules : {}">
    <a-spin :spinning="loading">
      <!-- 表格 -->
      <a-card :bordered="false">
        <title-name title="基本信息" />
        <!--@popupScroll="(name, e) => (popupScrollArr.includes(name) ? handleScroll(name, e) : null)"-->
        <custom-form :form-list="state == 3 ? formListDetail : formList" :form="form" :edit-model="state == 3 ? 'V' : ''" @getOption="(name, e) => getOption(name, e)" @selectOrg="selectOrg" />
      </a-card>
      <!--附件-->
      <div>
        <attachment :attachment="form.fileInfoList" :disabled="state == 3 ? false : true" @change="(e) => (form.fileInfoList = e)" />
      </div>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top">
      <a-button v-if="state != 3" :loading="loadingSav" type="primary" class="button_right" @click="handleSubmit(1)"> 保存草稿 </a-button>
      <a-button v-if="state != 3" :loading="loadingSub" type="primary" class="button_right" @click="handleSubmit(2)"> 提交 </a-button>
      <a-button v-if="state != 3" type="primary" @click="handleActiveClose"> 关闭 </a-button>
    </div>
     <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </a-form-model>
</template>

<script>
import { create, edit, detail, getLabels } from '@/api/legal/change'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import Selector from '@/components/Select/Selector'
import moment from 'moment'
import attachment from './attachment' // 附件

export default {
  extends: new BaseEditPage(),
  components: {
    attachment
  },
  props: {
    state: {
      type: [String, Number]
    }
  },
  data() {
    return {
      loading: false, // 加载控件
      loadingSav: false,
      loadingSub: false,
      isEmpty: false, //码表数据是否清空
      contractChangeDisabled: true,
      // state: this.$route.query.state,
      contractChangeType: '',
      contractTypeMainArr: [
        {
          name: '是',
          id: '1'
        },
        {
          name: '否',
          id: '0'
        }
      ],
      contractChangeArr: [],
      // allowClear:false,
      form: {
        viewName: "",
        fileInfoList: [],
        applyUnit: '中国建筑第八工程局有限公司西南分公司',
        createTime: this.moment(new Date()),
        launchUnitId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
      }, // 表单
      rules: {
        projectFormat: { required: true, message: '请选择项目业态', trigger: 'change' },
        projectType: { required: true, message: '请选择项目类型', trigger: 'change' },
        buildTypeId: { required: true, message: '请选择建设单位性质', trigger: 'change' },
        signDate: { required: true, message: '请选择签约时间', trigger: 'change' },

        contractName: [{ required: true, message: '请输入合同名称', trigger: 'change' }],
        applyUnit: [{ required: true, message: '请输入申请单位', trigger: 'change' }],
        branchComId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        otherParty: [{ required: true, message: '请输入相对方', trigger: 'change' }],
        contractTypeMainId: [{ required: true, message: '请选择主合同类型', trigger: 'change' }],
        contractChangeId: [{ required: true, message: '请选择变更类型', trigger: 'change' }],
        majorRisk: [{ required: true, message: '请选择主合同是否有重大风险', trigger: 'change' }],
        advanceAmount: [{ required: true, message: '请输入主合同价款(万元)', trigger: 'change' }],
        changeAmount: [{ required: true, message: '请输入变更合同价款(万元)', trigger: 'change' }],
        changeContent: [{ required: true, message: '请输入合同变更内容', trigger: 'change' }],
        creatorName: [{ required: true, message: '自动带出', trigger: 'change' }],
        createTime: [{ required: true, message: '自动带出', trigger: 'change' }]
      }, // 校验规则
      init: false, // 初始化控件
       //获取流程配置值
      processConfig: null,
       //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    formList() {
      let statusBool = [
        {
          label: '是',
          value: '1'
        },
        {
          label: '否',
          value: '0'
        }
      ]
      return [
        {
          keyName: 'contractName',
          type: 'a-input',
          label: '合同名称',
          span: 24
        },

        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth: true,
          checkStrictly: true,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        // {
        //     type: SelectSubCompany,
        //     keyName: 'branchComId',
        //     viewName: 'branchComName',
        //     label: '所属分公司',
        //     attrs: {
        //         // getAll: true
        //         // labelInValue:true
        //     }
        // },
        // {
        //     type: SelectProject,
        //     keyName: 'projectId',
        //     viewName: 'projectName',
        //     label: '项目名称',
        //     attrs: {
        //         keyValue: 'branchComId',
        //         autoSelected: true,
        //         isClear: true
        //         // labelInValue:true
        //     }
        // },
        {
          keyName: 'otherParty',
          type: 'a-input',
          label: '建设单位名称'
        },

        {
          type: Selector,
          keyName: 'buildTypeId',
          viewName: 'buildTypeStr',
          label: '建设单位性质',
          attrs: {
            customQueryType: {
              query: {
                type: 29
              }
            },
            urlType: 'legalChange'
          }
        },
        {
          keyName: 'signDate',
          type: 'a-date-picker',
          label: '签约时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: this.disabledDate2
          }
        },
        {
          type: Selector,
          keyName: 'projectFormat',
          viewName: 'projectFormatStr',
          label: '项目业态',
          attrs: {
            customQueryType: {
              query: {
                type: 18
              }
            },
            urlType: 'legalChange'
          }
        },
        {
          type: Selector,
          keyName: 'projectType',
          viewName: 'projectTypeStr',
          label: '项目类型',
          attrs: {
            customQueryType: {
              query: {
                type: 19
              }
            },
            urlType: 'legalChange'
          }
        },
        {
          keyName: 'applyUnit',
          type: 'a-input',
          disabled: true,
          label: '申请单位',
          span: 24
        },
        {
          type: Selector,
          keyName: 'contractTypeMainId',
          viewName: 'contractTypeMainName',
          label: '主合同类型',
          attrs: {
            customQueryType: {
              query: {
                type: '23'
              }
            },
            urlType: 'legalChange'
            // labelInValue: true,
            // isDefault: true
          }
        },
        {
          type: Selector,
          keyName: 'contractChangeId',
          viewName: 'contractChangeName',
          label: '变更类型',
          disabled: this.contractChangeDisabled,
          attrs: {
            mode: 'multiple',
            isEmpty: this.isEmpty, //是否为空
            customQueryType: {
              query: {
                type: this.contractChangeType
              }
            },
            urlType: 'legalChange'
            // labelInValue: true,
            // isDefault: false
          },
          span: 16
        },
        {
          keyName: 'majorRisk',
          viewName: 'majorRiskName',
          label: '主合同是否有重大风险',
          type: 'a-select',
          data: statusBool
        },
        {
          keyName: 'advanceAmount',
          type: 'a-input-number',
          label: '主合同价款(万元)',
          precision: 2,
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'changeAmount',
          type: 'a-input-number',
          label: '变更合同价款(万元)',
          precision: 2,
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'changeContent',
          type: 'BaseTextarea',
          label: '合同变更内容',
          span: 24
        },
        {
          keyName: 'creatorName',
          type: 'a-input',
          disabled: true,
          label: '创建人'
        },
        {
          keyName: 'createTime',
          viewName: 'createTime',
          type: 'a-date-picker',
          placeholder: '创建时间',
          label: '创建时间',
          disabled: true,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        }
      ]
    },
    formListDetail() {
      let statusBool = [
        {
          label: '是',
          value: '1'
        },
        {
          label: '否',
          value: '0'
        }
      ]
      return [
        {
          keyName: 'contractName',
          type: 'a-input',
          label: '合同名称',
          span: 24
        },
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth: true,
          checkStrictly: true,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          isNoBorder: this.state == 3,
          viewName: "viewName"
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   viewName: 'branchComName',
        //   label: '所属分公司',
        //   attrs: {
        //     // getAll: true
        //     // labelInValue:true
        //   },
        //   span: 24
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   viewName: 'projectName',
        //   label: '所属项目',
        //   attrs: {
        //     keyValue: 'branchComId',
        //     autoSelected: true,
        //     isClear: false
        //     // labelInValue:true
        //   },
        //   span: 12
        // },
        {
          keyName: 'otherParty',
          type: 'a-input',
          label: '建设单位名称',
          span: 12
        },
        {
          type: Selector,
          keyName: 'buildTypeId',
          viewName: 'buildTypeStr',
          label: '建设单位性质',
          attrs: {
            customQueryType: {
              query: {
                type: 29
              }
            },
            urlType: 'legalChange'
          },
          span: 12
        },
        {
          keyName: 'signDate',
          type: 'a-input',
          label: '签约时间',
          span: 12
        },
        {
          type: Selector,
          keyName: 'projectFormat',
          viewName: 'projectFormatStr',
          label: '项目业态',
          attrs: {
            customQueryType: {
              query: {
                type: 18
              }
            },
            urlType: 'legalChange'
          },
          span: 12
        },
        {
          type: Selector,
          keyName: 'projectType',
          viewName: 'projectTypeStr',
          label: '项目类型',
          attrs: {
            customQueryType: {
              query: {
                type: 19
              }
            },
            urlType: 'legalChange'
          },
          span: 12
        },
        {
          keyName: 'applyUnit',
          type: 'a-input',
          disabled: true,
          label: '申请单位',
          // span: 24,
          span: 12
        },
        {
          type: Selector,
          keyName: 'contractTypeMainId',
          viewName: 'contractTypeMainName',
          label: '主合同类型',
          attrs: {
            customQueryType: {
              query: {
                type: '23'
              }
            },
            urlType: 'legalChange'
            // labelInValue: true,
            // isDefault: true
          },
          span: 12
        },
        {
          type: Selector,
          keyName: 'contractChangeId',
          viewName: 'contractChangeName',
          label: '变更类型',
          attrs: {
            mode: 'multiple',
            isEmpty: this.isEmpty, //是否为空
            customQueryType: {
              query: {
                type: this.contractChangeType
              }
            },
            urlType: 'legalChange'
            // labelInValue: true,
            // isDefault: false
          },
          span: 12
        },
        {
          keyName: 'majorRisk',
          viewName: 'majorRiskName',
          label: '主合同是否有重大风险',
          type: 'a-select',
          data: statusBool,
          span: 12
        },
        {
          keyName: 'advanceAmount',
          type: 'a-input',
          label: '主合同价款(万元)',
          precision: 2,
          attrs: {
            min: 0
          },
          span: 12
        },
        {
          keyName: 'changeAmount',
          type: 'a-input',
          label: '变更合同价款(万元)',
          precision: 2,
          attrs: {
            min: 0
          },
          span: 12
        },
        {
          keyName: 'changeContent',
          type: 'BaseTextarea',
          label: '合同变更内容',
          // span: 24,
          span: 12
        },
        {
          keyName: 'creatorName',
          type: 'a-input',
          disabled: true,
          label: '创建人',
          span: 12
        },
        {
          keyName: 'createTime',
          viewName: 'createTime',
          type: 'a-date-picker',
          placeholder: '创建时间',
          label: '创建时间',
          disabled: true,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          },
          span: 12
        }
      ]
    }
  },
  watch: {},
 async mounted() {
    this.$route.meta.title = ['总包合同变更新增', '总包合同变更编辑', '总包合同变更查看'][this.state - 1];
    if(this.$route.query.type*1 === 10){
      //获取通过获取流程配置值
      this.processConfig = await this.$getConfigFn('LEGAL_GENERAL_CHANGE');
    }
    /**
     * 不为添加时请求详情
     * state 新增：1， 编辑：2， 查看：3
     * */
    if (this.state != 1) {
      this.loading = true
      detail({ id: this.$route.query.id })
        .then((res) => {
          this.loading = false
          this.form = res.data
          if (this.state == 3) {
            this.form.contractTypeMainName = res.data.contractTypeVO.name
            this.form.majorRiskName = res.data.majorRisk == 1 ? '是' : res.data.majorRisk == 0 ? '否' : ''
          } else {
            this.form.contractChangeId = res.data.contractChangeId ? res.data.contractChangeId.split(',') : []
            this.form.createTime = this.moment(res.data.createTime)
            this.form.majorRisk = res.data.majorRisk.toString()
          }
          this.form.viewName = this.form.branchComName + '/' + this.form.projectName
          console.log( this.form.viewName, 111111111111)
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
    /**
     * 分类23
     **/
    // this.handleGetLabels({ query: { type: '23' } })
  },
  methods: {
    //选择单位
    selectOrg(val) {
      if (val && val.length) {
        this.form.branchComId = val[val.length - 2].orgId
      }
    },
    disabledDate2(current) {
      return current && current > moment()
    },
    getOption(name, e) {
      if (name === 'contractTypeMainId') {
        if (e) {
          this.isEmpty = true
          this.contractChangeDisabled = false
          if (e.id === '719445626064080896') {
            // "承包类"
            this.contractChangeType = '24'
          } else if (e.id === '719445715411144704') {
            // "分包分供类"
            this.contractChangeType = '25'
          }
        }
      }
    },
    // handleGetLabels(e) {
    //     getLabels(e)
    //         .then((res) => {
    //             if (e.query.type === '23') {
    //                 this.contractTypeMainArr = res.data
    //             } else if (e.query.type === '24' || e.query.type === '25') {
    //                 this.contractChangeArr = res.data
    //             }
    //         })
    //         .catch(() => {})
    // },
    /**
     * 校验表单
     */
    handleSubmit(val) {
      if (val == '2') {
        // 提交表单
        // 校验表单
        this.$refs.ruleForm.validate((e) => {
          if (e) {
            if (this.form.fileInfoList.length > 0) {
              this.handleSubmitApi(val)
            } else {
              this.$notification['error']({
                message: '请上传附件'
              })
            }
          }
        })
      } else {
        //保存表单
        this.handleSubmitApi(val)
      }
    },
    /**
     * 提交表单
     */
    handleSubmitApi(val) {
      let that = this
      that.setProcessConfig = null; 
      let api = ''
      if (this.$route.query.id) {
        api = edit // 根据操作切换url地址
      } else {
        api = create // 根据操作切换url地址
      }
      that.loading = true

      that.submitApprovalConfirm(val == 2?this.processConfig:6,(flag)=>{
        if(!flag) {
            that.loadingSub = false
            that.loadingSav = false
            return
          }
        if (val == '2') {
        that.loadingSub = true
      } else {
        that.loadingSav = true
      }
      let formData = that.$clone(that.form)
      console.log(formData.contractChangeId)
      let form = {
        ...formData,
        contractChangeId: formData.contractChangeId ? formData.contractChangeId.toString() : null,
        contractChangeName: '', //可不传
        commonFileIds: formData.fileInfoList ? formData.fileInfoList.map((item) => item.commonId) : [],
        contractChangeStatus: formData.contractChangeStatus === 'REJECTED' ? 'REJECTED' : val == '2' ? 'SUBMITTED' : 'DRAFT' //结果已提交未反馈：NO_FEEDBACK； 待提交：DRAFT
      }
      api(form)
        .then((res) => {
          that.loading = false
          if (val == '2') {
            that.$message.success('提交成功！')
            that.loadingSub = false
            //提交时，返回id
            that.businessId = res.data.baseId;
            that.setProcessConfig = this.processConfig;
          } else {
            that.$message.success('保存成功！')
            that.loadingSav = false
            that.$multiTab.close()
          }
        })
        .catch(() => {
          that.loading = false
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.file_prompt {
  color: #999;
}
</style>
